<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>canvas 绘制折线统计图</title>
</head>
<body>

    <canvas id="canvas" height="500" width="600"></canvas>

    <script>

        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');

        const cvsH = canvas.height;
        const cvsW = canvas.width;

        const originPos = [50, 400];
        const xEndPos = [50, 50];
        const yEndPos = [600, 400];

        function renderAxis(){  

            ctx,beginPath();
            ctx.moveTo(...originPos);
            ctx.lineTo(...xEndPos);

            ctx.moveTo(...originPos);
            ctx.lineTo(...yEndPos);

            ctx.moveTo(...xEndPos);
            ctx.lineTo(xEndPos[0] - 10, xEndPos[1] + 10);
            ctx.moveTo(...xEndPos);
            ctx.lineTo(xEndPos[0] + 10, xEndPos[1] + 10);

            ctx.moveTo(...yEndPos);
            ctx.lineTo(yEndPos[0] - 10, yEndPos[1] - 10);
            ctx.moveTo(...yEndPos);
            ctx.lineTo(yEndPos[0] - 10, yEndPos[1] + 10);

            ctx.strokeStyle = "#f22";
            ctx.stroke();
        }

        renderAxis();

        const dataArr = [.1, .6, .4, .5, .9];
        // 绘制坐标点
        function renderDots(data) {
            const len = data.length;
            // 计算出坐标点之间的间隔
            const spaceW = (yEndPos[0] - originPos[0]) / len;
            
            const axisHeight = yEndPos[1] - xEndPos[1];

            const dots = data.map(item => axisHeight - item * axisHeight);

            // 绘制
            ctx.beginPath();
            ctx.lineWidth = 3;
            ctx.moveTo(...originPos);
            for(let i = 1;i <= len;i ++){
                let xPos = i * spaceW + originPos[0];
                console.log(xPos);
                ctx.lineTo(xPos, dots[i - 1]);
            }

            ctx.strokeStyle = 'green';
            ctx.stroke();
        }

        renderDots(dataArr);

    </script>
    
</body>
</html>